// http://127.0.0.1:8900/apif  || https://meituan.thexxdd.cn/apif
//http://47.92.92.92/apif
const baseURL = 'https://www.lvyou-api.zhoutaotao.cn/apif';
// const baseURL = 'http://127.0.0.1:8908/apif';
import { Base64 } from 'js-base64';

// 对token加密
function encryptToken(){
	const {user_Token} = wx.getStorageSync('userInfor')//从本地缓存里取出token
	const auth = Base64.encode(user_Token + ':')//对token加密
	return 'Basic ' + auth
}
// 提示
function showToast(title:string){
	wx.showToast({
		title,
		icon: 'none',
		duration: 1000,
	});
}
type Data<T> = {
    msg: string;
    data: T;
    error:string
    extra:string
}

// 拦截器配置
const httpInterceptor = {
    // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非 http 开头需拼接地址
      options.url = baseURL + options.url
    // 2. 请求超时
    options.timeout = 10000
    // 3. 添加小程序端请求头标识
    options.header = {
      'source-client': 'miniapp',
      ...options.header,
    }
  },
}

// 请求
function requestApi<T>(options:UniApp.RequestOptions){
	return new Promise<Data<T>>((resolve, reject) => {
		uni.request({
            ...options,
			header: { Authorization: encryptToken() },
			success: (res) => {
				const status =  res.statusCode
				switch (status){
					case 200:
					resolve(res.data as Data<T>);
					wx.hideLoading()
					break;
					case 404:
					console.error('接口不存在')
					reject('404');
					wx.hideLoading()
					break;
					case 401:
					wx.navigateTo({ url: '/pages/login/login'});
					console.error('没有权限')
					reject('401');
					wx.hideLoading()
					break;
					case 500:
					console.error(res.data)
					showToast('发生异常错误');
					reject('500');
					wx.hideLoading()
					break;
					case 501:
					console.error(res.data)
					showToast('发生异常错误');
					reject('501');
					console.error(res.data)
					wx.hideLoading()
					break;
					case 502:
					console.error(res.data)
					showToast('发生异常错误');
					reject('502');
					wx.hideLoading()
					break;
					case 400:
					console.error((res.data as Data<T>).msg)
					reject('400');
					wx.hideLoading()
					break;
					case 422:
					showToast((res.data as Data<T>).msg);
					reject('422');
					wx.hideLoading()
					break;
				}
			},
			fail: (err) => {
				reject(err);
				wx.hideLoading()
			},
		});
	});
}
// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
export { requestApi };